import type { FC } from "react";
import { Button, message } from "antd";
import Navbar from "@/layout/Navbar";
import useUserStore from "@/models/user";
import { useMemoizedFn, useSafeState } from "ahooks";
import { Respone } from "@/libs/request/respone";
import { ProForm, ProFormText } from "@ant-design/pro-components";

import styles from "./styles.module.less";

type ValueType = {
  acnt: string;
  password: string;
}

const Login: FC = () => {
  const user = useUserStore();
  const [loading, setLoading] = useSafeState(false);

  // login
  const onLogin = useMemoizedFn(async (values: ValueType) => {
    setLoading(true);
    try {
      await user.userLogin(
        values.acnt,
        values.password
      );
    } catch (err: any) {
      if (err instanceof Respone) {
        message.error(err.message);
      }
    }
    setLoading(false);
  });

  return (
    <div className={styles.login}>
      <Navbar />
      <div className={styles.login_form}>
        <div className={styles.header}>登录</div>
        <ProForm<ValueType>
          size="large"
          layout="vertical"
          onFinish={onLogin}
          submitter={false}
          initialValues={{
            acnt: "barry.y.liu@gmail.com",
            password: "R00t@dm1n"
          }}
        >
          <ProFormText
            name="acnt"
            required={false}
            placeholder="用户名"
            rules={[
              { required: true, type: "email" }
            ]}
          />
          <ProFormText.Password
            name="password"
            required={false}
            placeholder="密码"
            rules={[
              { required: true }
            ]}
          />
          <Button
            block
            type="primary"
            loading={loading}
            htmlType="submit"
          >
            登录
          </Button>
        </ProForm>
      </div>
    </div>
  );
};

export default Login;
